package com.ld.hpfs.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ld.hpfs.common.utils.Tools;
import com.ld.hpfs.dao.EnterInvoiceMapper;
import com.ld.hpfs.dao.HistoryMapper;
import com.ld.hpfs.service.HistoryService;

@Service
public class HistoryServiceImpl implements HistoryService {
	private static final Logger logger = LoggerFactory
			.getLogger(MdataServiceImpl.class);
	@Autowired
	private HistoryMapper historyMapper;

	@Autowired
	private EnterInvoiceMapper enterInvoiceMapper;

	@Override
	public void addMdataClientHistory(HashMap<String, Object> params,
			boolean edit) {
		ArrayList<HashMap<String, Object>> histories = historyMapper
				.getMdataClientInfo(params);
		for (HashMap<String, Object> history : histories) {
			history.put("action", edit);
			history.put("uid", params.get("update_id"));
			history.put("uname", params.get("update_name"));
			historyMapper.addMdataClientHistory(history);
		}

		// 如果为删除，还需删除该客户的所有联系方式
		if (!edit) {
			this.addMdataClientContactHistory(params, edit);
		}

	}

	@Override
	public void addMdataClientContactHistory(HashMap<String, Object> params,
			boolean edit) {
		ArrayList<HashMap<String, Object>> histories = historyMapper
				.getMdataClientContactInfo(params);
		for (HashMap<String, Object> history : histories) {
			history.put("action", edit);
			history.put("uid", params.get("update_id"));
			history.put("uname", params.get("update_name"));
			historyMapper.addMdataClientContactHistory(history);
		}
	}

	@Override
	public void addMdataGoodHistory(HashMap<String, Object> params, boolean edit) {
		ArrayList<HashMap<String, Object>> histories = historyMapper
				.getMdataGoodsInfo(params);

		for (HashMap<String, Object> history : histories) {
			history.put("action", edit);
			history.put("uid", params.get("update_id"));
			history.put("uname", params.get("update_name"));
			historyMapper.addMdataGoodsHistory(history);
		}
	}

	@Override
	public void addMdataBankAccountHistory(HashMap<String, Object> params,
			boolean edit) {
		ArrayList<HashMap<String, Object>> histories = historyMapper
				.getMdataBankAccountInfo(params);

		for (HashMap<String, Object> history : histories) {
			history.put("action", edit);
			history.put("uid", params.get("update_id"));
			history.put("uname", params.get("update_name"));
			historyMapper.addMdataBankAccountHistory(history);
		}

	}

	@Override
	public void addCompanyHistory(HashMap<String, Object> params, boolean edit) {
		int id = Integer.parseInt(params.get("id").toString());
		ArrayList<HashMap<String, Object>> histories = historyMapper
				.getCompanyInfo(id);

		if (histories != null && histories.size() > 0) {
			HashMap<String, Object> history = histories.get(0);
			history.put("action", edit);
			history.put("uid", params.get("update_id"));
			history.put("uname", params.get("update_name"));
			historyMapper.addCompanyHistory(history);
		}
	}

	@Override
	public void addTicketHistory(HashMap<String, Object> params, boolean edit) {
		ArrayList<HashMap<String, Object>> histories = historyMapper
				.getTicketInfo(params);

		if (histories != null && histories.size() > 0) {
			HashMap<String, Object> history = histories.get(0);
			history.put("action", edit);
			history.put("uid", params.get("update_id"));
			history.put("uname", params.get("update_name"));
			historyMapper.addTicketHistory(history);
		}

	}

	@Override
	public void addInputDbSourceHistory(HashMap<String, Object> params,
			boolean edit) {
		ArrayList<HashMap<String, Object>> histories = historyMapper
				.getInputDbSourceInfo(params);

		if (histories != null && histories.size() > 0) {
			HashMap<String, Object> history = histories.get(0);
			history.put("action", edit);
			history.put("uid", params.get("update_id"));
			history.put("uname", params.get("update_name"));
			historyMapper.addInputDbSourceHistory(history);
		}

	}

	@Override
	public void addOutputDbSourceHistory(HashMap<String, Object> params,
			boolean edit) {
		ArrayList<HashMap<String, Object>> histories = historyMapper
				.getOutputDbSourceInfo(params);

		if (histories != null && histories.size() > 0) {
			HashMap<String, Object> history = histories.get(0);
			history.put("action", edit);
			history.put("uid", params.get("update_id"));
			history.put("uname", params.get("update_name"));
			historyMapper.addOutputDbSourceHistory(history);
		}
	}

	@Override
	public void addUserHistory(HashMap<String, Object> params, boolean edit) {
		ArrayList<HashMap<String, Object>> histories = historyMapper
				.getUserInfo(params);

		if (histories != null && histories.size() > 0) {
			HashMap<String, Object> history = histories.get(0);
			history.put("action", edit);
			history.put("uid", params.get("update_id"));
			history.put("update_name", params.get("update_name"));
			historyMapper.addUserHistory(history);
		}

		// 将原有的Role与现有的Role进行比对，将更改的记录加入HPFS_H_USER_ROLE中
		// 若原有Role被删除，ACTION为0
		// 若新添加Role，ACTION为1
		ArrayList<HashMap<String, Object>> old_roles = historyMapper
				.getUserRoleInfo(params);
		String[] new_roles = (String[]) params.get("roles");
		ArrayList<HashMap<String, Object>> add_roles = new ArrayList<HashMap<String, Object>>();

		// 检索新加的Role
		for (int i = 0; i < new_roles.length; i++) {
			boolean found = false;
			for (HashMap<String, Object> role : old_roles) {
				if (role.get("rid").toString().equals(new_roles[i])) {
					found = true;
					break;
				}
			}
			if (!found) {
				HashMap<String, Object> new_role = new HashMap<String, Object>();
				new_role.put("rid", Integer.parseInt(new_roles[i]));
				new_role.put("id", params.get("id"));
				new_role.put("cid", params.get("update_id"));
				new_role.put("action", true);
				add_roles.add(new_role);
			}
		}

		// 检索被删除的Role
		for (HashMap<String, Object> role : old_roles) {
			boolean found = false;
			for (int i = 0; i < new_roles.length; i++) {
				if (role.get("rid").toString().equals(new_roles[i])) {
					found = true;
					break;
				}
			}
			if (!found) {
				HashMap<String, Object> new_role = role;
				new_role.put("action", false);
				add_roles.add(new_role);
			}
		}

		// 添加进用户角色History表
		for (HashMap<String, Object> add_role : add_roles) {
			add_role.put("uid", params.get("update_id"));
			add_role.put("uname", params.get("update_name"));
			historyMapper.addUserRoleHistory(add_role);
		}

	}

	@Override
	public void addUserPermissionHistory(HashMap<String, Object> params) {
		// 将原有的Company与现有的Company进行比对，将更改的记录加入HPFS_H_USER_COMPANY中
		// 若原有Company被删除，ACTION为0
		// 若新添加Company，ACTION为1
		ArrayList<HashMap<String, Object>> old_companies = historyMapper
				.getUserPermissionInfo(params);
		String[] new_companies = (String[]) params.get("companies");
		ArrayList<HashMap<String, Object>> add_companies = new ArrayList<HashMap<String, Object>>();

		// 检索新加的Company
		for (int i = 0; i < new_companies.length; i++) {
			boolean found = false;
			for (HashMap<String, Object> company : old_companies) {
				if (company.get("cpn_id").toString().equals(new_companies[i])) {
					found = true;
					break;
				}
			}
			if (!found) {
				HashMap<String, Object> new_company = new HashMap<String, Object>();
				new_company.put("cpn_id", Integer.parseInt(new_companies[i]));
				new_company.put("id", params.get("id"));
				new_company.put("cid", params.get("update_id"));
				new_company.put("action", true);
				add_companies.add(new_company);
			}
		}

		// 检索被删除的Company
		for (HashMap<String, Object> company : old_companies) {
			boolean found = false;
			for (int i = 0; i < new_companies.length; i++) {
				if (company.get("cpn_id").toString().equals(new_companies[i])) {
					found = true;
					break;
				}
			}
			if (!found) {
				HashMap<String, Object> new_company = company;
				new_company.put("action", false);
				add_companies.add(new_company);
			}
		}

		// 添加进用户数据权限History表
		for (HashMap<String, Object> add_company : add_companies) {
			add_company.put("uid", params.get("update_id"));
			add_company.put("uname", params.get("update_name"));
			historyMapper.addUserPermissionHistory(add_company);
		}

	}

	@Override
	public int addInvoiceHeadHistory(HashMap<String, Object> params,
			int action, boolean flag) {

		// 添加动作、变更信息到票据变更动作履历表，并得到该变更的履历编号
		int histId = 0;
		ArrayList<Integer> headIds = (ArrayList<Integer>) params.get("headIds");
		if (!flag) {
			// 变更前
			if (action == 0 || action == 1) { // 删除、编辑时，变更前添加动作表获取histId
				for (int i = 0; i < headIds.size(); i++) {
					HashMap<String, Object> newParams = historyMapper
							.getDocNoInfo(headIds.get(i));
					params.put("headId", headIds.get(i));
					params.put("action", action);
					params.put("companyId", newParams.get("companyId")
							.toString());
					params.put("docNo", newParams.get("docNo").toString());
					if (i == 0) {
						histId = historyMapper.getMaxHistId();
						params.put("histId", histId);
						historyMapper.addInvoiceHistory(params);
					} else {
						historyMapper.addInvoiceHistory(params);
					}
				}
			} else { // 拆分、合并、规律时，添加变更前数据时，已有histId
				histId = Integer.parseInt(params.get("histId").toString());
			}
		} else {
			// 变更后
			if (action == 0 || action == 1) { // 删除、编辑时，添加变更后数据时，已有histId
				histId = Integer.parseInt(params.get("histId").toString());
			} else { // 拆分、合并、规律时，变更后添加动作表获取histId
				for (int i = 0; i < headIds.size(); i++) {
					HashMap<String, Object> newParams = historyMapper
							.getDocNoInfo(headIds.get(i));
					params.put("headId", headIds.get(i));
					params.put("action", action);
					params.put("companyId", newParams.get("companyId")
							.toString());
					params.put("docNo", newParams.get("docNo").toString());
					if (i == 0) {
						histId = historyMapper.getMaxHistId();
						params.put("histId", histId);
						historyMapper.addInvoiceHistory(params);
					} else {
						historyMapper.addInvoiceHistory(params);
					}
				}
			}
		}

		for (int i = 0; i < headIds.size(); i++) {
			params.put("headId", headIds.get(i));
			ArrayList<HashMap<String, Object>> histories = historyMapper
					.getInvoiceHeadMainInfo(params);
			String type = "";
			if (histories != null && histories.size() > 0) {
				HashMap<String, Object> history = histories.get(0);
				history.put("histId", histId);
				history.put("flag", flag);
				type = history.get("DOC_TYPE_CODE").toString();
				historyMapper.addInvoiceHeadMainHistory(history);
			}
			this.addInvoiceDetailHistory(params, histId, flag, type);

			if (type.equals("E_INV")) {// 进出口发票

				ArrayList<HashMap<String, Object>> exps = historyMapper
						.getInvoiceHeadExpInfo(params);
				if (exps != null && exps.size() > 0) {
					HashMap<String, Object> history = exps.get(0);
					history.put("histId", histId);
					history.put("flag", flag);
					historyMapper.addInvoiceHeadExpHistory(history);
				}

			} else if (type.equals("T_INV")) {// 运输类发票

				ArrayList<HashMap<String, Object>> exps = historyMapper
						.getInvoiceHeadTransInfo(params);
				if (exps != null && exps.size() > 0) {
					HashMap<String, Object> history = exps.get(0);
					history.put("histId", histId);
					history.put("flag", flag);
					historyMapper.addInvoiceHeadTransHistory(history);
				}
			}
		}
		return histId;
	}

	/**
	 * 增加发票明细履历 如果是交通运输发票，自动更新交通运输特有表格
	 * 
	 * @param params
	 *            包含headId, user_id和user_name （有可能有detailId）
	 * @param edit
	 *            true表示动作为编辑，false表示动作为删除
	 */
	private void addInvoiceDetailHistory(HashMap<String, Object> params,
			int histId, boolean flag, String type) {

		ArrayList<HashMap<String, Object>> details = historyMapper
				.getInvoiceDetailInfo(params);
		System.out.println(details.size());
		for (HashMap<String, Object> detail : details) {
			detail.put("histId", histId);
			detail.put("flag", flag);
			historyMapper.addInvoiceDetailHistory(detail);

			// 添加运输history表
			if (type.equals("T_INV")) {
				params.put("detailId",
						Integer.parseInt(detail.get("ID_DETAIL_ID").toString()));
				ArrayList<HashMap<String, Object>> trans = historyMapper
						.getInvoiceDetailTransInfo(params);
				if (trans != null && trans.size() > 0) {
					HashMap<String, Object> tran = trans.get(0);
					tran.put("histId", histId);
					tran.put("flag", flag);
					historyMapper.addInvoiceDetailTransHistory(tran);
				}
			}
		}
	}

	@Override
	public HashMap<Integer, ArrayList<Integer>> getSplitMergeInfo(
			String[] originalIds, boolean split) {
		HashMap<Integer, ArrayList<Integer>> result = new HashMap<Integer, ArrayList<Integer>>();
		if (split) {
			// 拆分时，将数据存成：原始Id -> 新ids
			for (int i = 0; i < originalIds.length; i++) {
				ArrayList<HashMap<String, Object>> splits = historyMapper
						.getSplitInfo(Integer.parseInt(originalIds[i]));
				if (splits != null && splits.size() > 0) {
					ArrayList<Integer> children = new ArrayList<Integer>();
					for (HashMap<String, Object> child : splits) {
						children.add(Integer.parseInt(child.get("headId")
								.toString()));
					}
					result.put(Integer.parseInt(originalIds[i]), children);
				}
			}
		} else {
			// 合并时，将数据存成：新id -> 原始ids

			// 先得到所有新生成单据的headId
			HashMap<String, Object> params = new HashMap<String, Object>();
			ArrayList<HashMap<String, Object>> ids = new ArrayList<HashMap<String, Object>>();
			for (int i = 0; i < originalIds.length; i++) {
				HashMap<String, Object> id = new HashMap<String, Object>();
				id.put("headId", Integer.parseInt(originalIds[i]));
				ids.add(id);
			}
			params.put("list", ids);
			ArrayList<HashMap<String, Object>> newIds = historyMapper
					.getMergeIds(params);

			// 当有新单据生成时，根据新单据headId获取合并成它的原始单据headId
			if (newIds != null && newIds.size() > 0) {
				for (HashMap<String, Object> newId : newIds) {
					int headId = Integer.parseInt(newId.get("headId")
							.toString());
					ArrayList<HashMap<String, Object>> merges = historyMapper
							.getMergeInfo(headId);
					if (merges != null && merges.size() > 0) {
						ArrayList<Integer> parents = new ArrayList<Integer>();
						for (HashMap<String, Object> parent : merges) {
							parents.add(Integer.parseInt(parent.get("headId")
									.toString()));
						}
						result.put(headId, parents);
					}
				}
			}
		}
		return result;
	}

	@Override
	public void deleteInvoiceHistory(HashMap<String,Object> param) {
		ArrayList<HashMap<String, Object>> histIds = historyMapper.getHistoryByHeadId(param);
		if (histIds != null && histIds.size() > 0) {
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("list", histIds);
			historyMapper.deleteHistoryByHistId(params);
		}
	}

	@Override
	public ArrayList<HashMap<String, Object>> getHistoryByHeadid(HashMap<String,Object> param) {
		String cpnId = param.get("cpnId").toString();
		String document_no = param.get("document_no").toString();
		// 得到该票据的履历
		ArrayList<HashMap<String, Object>> result = historyMapper.getHistoryByHeadId(param);
		boolean recursive = (Boolean) param.get("flag");
		if (recursive) {
			// 得到该票据拆分、合并前的票据
			ArrayList<HashMap<String, Object>> parents = historyMapper
					.getParentsByHeadId(document_no);
			if (parents != null && parents.size() > 0) {
				for (HashMap<String, Object> parent : parents) {
					String parentdoc = parent.get("document_no").toString();
					
					HashMap<String,Object> paramfor = new HashMap<String,Object>();
					paramfor.put("cpnId", cpnId);
					paramfor.put("document_no", parentdoc);
					paramfor.put("falg", true);
					// 得到该老票据的所有履历
					ArrayList<HashMap<String, Object>> temp = this.getHistoryByHeadid(paramfor);
					// 加在新票据上
					result.addAll(0, temp);
				}
			}
		}
		// 反转排序,按时间由近到远排序
		Collections.reverse(result);
		// 截取前10条记录显示
		if (result.size() > 10) {
			for (int i = result.size(); i > 10; i--) {
				result.remove(i-1);
			}
		}
		return result;
	}

	@Override
	public ArrayList<HashMap<String, Object>> getInvoiceHeadHistoryByHistid(
			int histId, boolean flag, String language) {
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("histId", histId);
		params.put("flag", flag);
		params.put("language", language);
		return historyMapper.getInvoiceMainHistory(params);
	}

	@Override
	public ArrayList<HashMap<String, Object>> getInvoiceDetailHistoryByHistid(
			int histId, boolean flag) {
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("histId", histId);
		params.put("flag", flag);
		return historyMapper.getInvoiceDetailHistory(params);
	}

	@Override
	public void deleteInvoiceHistoryByDocNo(HashMap<String,Object> param) {
		ArrayList<HashMap<String, Object>> histories = historyMapper.getHistoryByDocNo(param);
		if (histories.size() != 0) {
			HashMap<String, Object> params = new HashMap<String, Object>();
			
			params.put("list", histories);
			historyMapper.deleteHistoryByHistId(params);
		}
	}

	@Override
	public String[] getChildrenByHeadId(String[] headIds) {
		ArrayList<String> result = new ArrayList<String>();
		for (int i = 0; i < headIds.length; i++) {
			ArrayList<HashMap<String, Object>> children = historyMapper
					.getChildrenByHeadId(Integer.parseInt(headIds[i]));
			if (children != null) {
				for (HashMap<String, Object> child : children) {
					result.add(child.get("headId").toString());
				}
			}
		}
		String[] arr = new String[result.size()];
		for (int i = 0; i < result.size(); i++) {
			arr[i] = result.get(i);
		}
		return arr;
	}

}
